package util
{
	import com.adobe.serialization.json.JSON;
	
	import flash.net.Socket;
	
	import mx.collections.ArrayCollection;
	
	public class SocketBusProvider implements BussnessProvider
	{
		private var _socket:Socket;
		
		public function SocketBusProvider(_socket:Socket)
		{
			this._socket = _socket;
		}

		public function doBussness(bussCode:String,objs:ArrayCollection):void
		{
			
			var header:Header = new Header(bussCode);
			
			var content:String = "{\"root\":";
			
			//单条数据
			if(objs.length==1){
			
				content = content.concat(JSON.encode(objs.getItemAt(0)));
				
			}else {
				content = content + "{size:\""+objs.length+"\",list:[";
				//多条数据
				for(var i:int = 0 ; i < objs.length;i++){
						
					if(i == objs.length-1){
						content = content + JSON.encode(objs.getItemAt(i));
					}else{
						content = content + JSON.encode(objs.getItemAt(i))+",";
					}
				}
				
				content = content + "]}";
			}
			
			content = content + "}";
			
			var blank:String = StringUtil.leftPad(Const.BLANKCHAR,Const.BLANK,Const.BLANKCHAR);
			
//			Alert.show(content.length.toString());
//			Alert.show(MD5.startMd(content));
			var body:Body = new Body(StringUtil.leftPad(content.length.toString(),Const.BODYLENGTH,Const.BLANKCHAR),MD5.startMd(content),blank,content);
			
			var msg:Message = new Message(header,body);
			
			_socket.writeUTFBytes(new FormatMSGImpl().format(msg)+" \n");
			_socket.flush();
		}
		
		public function get socket():Socket{
			return this._socket;
		}
		
		public function set socket(socket:Socket):void{
			this._socket = socket;
		}
		
	}
}